package com.lancoo.answer.view.fragment.listenmatch

import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.databinding.ObservableArrayList
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvFragmentListenMatchChildBinding
import com.lancoo.answer.databinding.EvViewItemOptionBinding
import com.lancoo.answer.helper.recyclerview.BindingViewAdapter
import com.lancoo.answer.helper.recyclerview.BindingViewHolder
import com.lancoo.answer.helper.recyclerview.SingleTypeAdapter
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.ChildOption
import com.lancoo.answer.model.bean.EvOptionBean
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.model.eventBean.CompleteCurrentAnsPointEventBean
import com.lancoo.answer.util.CustomPictureTextViewUtil
import com.lancoo.answer.util.ExamFontSizeAdjustUtils
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.view.fragment.option.adapter.ItemPresenter
import org.greenrobot.eventbus.EventBus

/**
 * @Description 听力匹配,听力排序
 * @Author dadong
 * @Date 05-23-2022 周一 11:37
 */
class ListenParagraphFragment : BaseVMFragment<EvFragmentListenMatchChildBinding>(),
    BindingViewAdapter.ItemDecorator, ItemPresenter {
    private var optionList = ObservableArrayList<EvOptionBean>()
    private lateinit var mAdapter: SingleTypeAdapter<EvOptionBean>
    private var callback: OptionCallback? = null
    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0
    private var itemSortIndex: String = "" //当前选择的序号

    companion object {
        fun loadFragment(typeIndex: Int, queseIndex: Int, defaultLoadIndex: Int): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, queseIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadIndex)
            val listenMatchChildFragment = ListenParagraphFragment()
            listenMatchChildFragment.arguments = mBundle
            return listenMatchChildFragment
        }
    }

    override fun initView(view: View) {

    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_listen_match_child
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        Log.e("0726", ""+typeIndex+","+quesIndex+","+",initData $defaultLoadIndex")
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        setOptionList(this.ques.ChildList!![0].ChildOptionList!!)
        if (defaultLoadIndex > 0 && defaultLoadIndex < ques.ChildList!![0].ItemList!!.size) {
            itemSortIndex = this.ques.ChildList!![0].ItemList!![defaultLoadIndex].ItemSortIndex!!
        } else {
            itemSortIndex = this.ques.ChildList!![0].ItemList!![0].ItemSortIndex!!
        }
        mBinding.childStatisticsView.setQues(ques)
        initWvAsk()
        initAdapter()
        updateCheck()
    }

    //选项的adapter
    private fun initAdapter() {
        mAdapter = SingleTypeAdapter(requireContext(), R.layout.ev_view_item_option, optionList)
        mBinding.optionRv.adapter = mAdapter.apply {
            itemPresenter = this@ListenParagraphFragment
            itemDecorator = this@ListenParagraphFragment
        }

        mBinding.optionRv.layoutManager = LinearLayoutManager(requireContext())
    }

    private fun initWvAsk() {
        mBinding.tvChildAsk.setDisableInterceptTouch(true)
        mBinding.tvChildAsk.setQues(ques)
        mBinding.tvChildAsk.initWebView(requireActivity(),
            ques.ChildList!![0].ChildAsk!!,
            object : InteractWebView.Callback {
                override fun finishCallback() {
                    wvLoadUrl(itemSortIndex)
                }

                override fun clickCallback(position: String) {
                    itemSortIndex = position
                    wvLoadUrl(position)
                    adjustFontSize()
                }
            })
    }

    //答题点下划线，高亮等等绘制
    private fun wvLoadUrl(position: String = "-1") {
        mBinding.tvChildAsk.scrollPosition(position)
        ques.ChildList!![0].ItemList!!.forEach {
            mBinding.tvChildAsk.loadUrl(
                it,
                position == it.ItemSortIndex.toString()
            )
        }
    }

    private fun updateCheck() {
        resetState()
        ques.ChildList!![0].ItemList!!.forEach { item ->
            optionList.forEach { evOptionBean ->
                if (item.StuAnswer == evOptionBean.OptionIndex) {
                    evOptionBean.SelectState = 2
                }
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    fun setOptionList(optionList: ArrayList<ChildOption>) {
        this.optionList.clear()
        optionList.forEach {
            val option = EvOptionBean().apply {
                Option = it.Option
                OptionIndex = it.OptionIndex
            }
            this.optionList.add(option)
        }
    }

    fun resetState() {
        optionList.forEach { it.SelectState = 0 }
    }

    override fun decorator(
        holder: BindingViewHolder<ViewDataBinding>?,
        position: Int,
        viewType: Int,
    ) {
        val itemBinding: EvViewItemOptionBinding = holder!!.binding as EvViewItemOptionBinding
        CustomPictureTextViewUtil(context, itemBinding.tvContent, itemBinding.item!!.Option)
        when (itemBinding.item!!.SelectState) {
            0 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_white)
                itemBinding.btnOption1.setTextColor(requireContext().resources.getColor(R.color.c333333))
            }
            1 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_blue)
                itemBinding.btnOption1.setTextColor(requireContext().resources.getColor(R.color.cffffff))
            }
            2 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_light_blue)
                itemBinding.btnOption1.setTextColor(requireContext().resources.getColor(R.color.cffffff))
            }
        }
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(itemBinding.tvIndex,14)
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(itemBinding.tvContent,14)
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(itemBinding.tvOption1,15)
    }


    fun setCallback(callback: OptionCallback) {
        this.callback = callback
    }

    interface OptionCallback {
        fun clickCallback(item: EvOptionBean)
    }

    //todo 多次点击导致多次跳转的优化
    override fun onItemClick(v: View, item: EvOptionBean) {
        item.SelectState = 1
        val position = getRealIndex()
        ques.ChildList!![0].ItemList!![position].StuAnswer = item.OptionIndex
        wvLoadUrl(itemSortIndex)
        itemSortIndex = (itemSortIndex.toInt() + 1).toString()
        dealOverSize()
        mAdapter.notifyDataSetChanged()
        Handler().postDelayed({
            item.SelectState = 2
            mAdapter.notifyDataSetChanged()
            //回显赋值
            val maxSize = ques.ChildList!![0].ItemList!!.size
            if (position == maxSize - 1) {
                FragmentCommunicationUtils.autoNextQuesFragment(this, true)
            }
            updateCheck()
            EventBus.getDefault().post(CompleteCurrentAnsPointEventBean())

        }, 200)
    }

    //处理itemSortIndex超过范围的情况
    fun dealOverSize() {
        val size = ques.ChildList!![0].ItemList!!.size
        val maxIndex = ques.ChildList!![0].ItemList!![size - 1].ItemSortIndex!!
        if (itemSortIndex.toInt() > maxIndex.toInt()) {
            itemSortIndex = maxIndex
        }
    }


    //获取序号在ItemList 中的位置
    fun getRealIndex(): Int {
        ques.ChildList!![0].ItemList!!.forEachIndexed { index, item ->
            if (item.ItemSortIndex == itemSortIndex) {
                return index
            }
        }
        return 0
    }

    fun setCurrentItem(itemIndex: Int) {
        itemSortIndex = this.ques.ChildList!![0].ItemList!![itemIndex].ItemSortIndex!!
        wvLoadUrl(itemSortIndex)
    }

    fun adjustFontSize() {
        if (mBinding.tvChildAsk != null) {
            mBinding.tvChildAsk.setFontSize()
        }
        mAdapter.notifyDataSetChanged()
    }


    fun markQuestion() {
        var isShow = 0
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    isShow = if (item.itemMark) { //
                        0
                    } else {
                        1
                    }
                    item.itemMark = !item.itemMark
                }
            }
        }
        val flagIndex = "znbkflag${itemSortIndex}"
        mBinding.tvChildAsk.showFlag(flagIndex, isShow)
    }
}